'use strict'
process.chdir(__dirname)

const titbit = require('titbit')
const fs = require('fs')
const pg = require('pg')
const dbconfig = require('./dbconfig.js')
//使用HTTP/1.1的客户端
const {httpcli} = require('gohttp')
const wxkey =require('./wxkey.js')

const tbloader = require('titbit-loader')

const token = require('titbit-token')
//引入然后初始化
let tok = new token({
    //token有效期，单位是秒
    expires:30,
    //必须是32位字母数字
    key:'qwertyuioplkjhgfdsazxcvbnm123456',
     //必须是16位字母数字
    iv:'zxcvbnmkjhgfdsa8'
})


let psql = new pg.Pool(dbconfig)
try {
    fs.accessSync('./images')
} catch (err) {
    fs.mkdirSync('./images')
}
let cert_path = '/usr/local/share'


const app = new titbit({
    debug: true,
    globalLog: true,
    cert: `${cert_path}/api.ymhjz.xyz.pem`,
    key: `${cert_path}/api.ymhjz.xyz.key`
})

let tb = new tbloader();
tb.init(app);
//添加一下两行，就是在addService对象上添加了一个属性

app.addService('tok',tok);
app.addService('psql',psql);

app.addService('imagePath',`${__dirname}/images`);






// content路由-end

app.get('/', async c => {
    c.send('ok')
})

app.get('/upload', async c => {
    //c.helper是助手函数模块，其中有对stream.pipe的封装
    //c.reply 是响应对象，http/1.1中指向response,http/2中指向stream。
    await c.helper.pipe('./upload.html', c.reply)
})


app.get('/user/:name/:age/:mobile', async c => {
    console.log(c.param)
    c.send(c.param);
})
//JS无需加分号，谁用谁知道，有时也得加分号，括号开头很重要
// ;(async()=>{})();
app.get('/mp-login/:code', async c => {
    let auth_url = `https://api.weixin.qq.com/sns/jscode2session` +
    `?appid=${wxkey.appid}`
    + `&secret=${wxkey.secret}`
    + `&js_code=${c.param.code}`
    + `&grant_type=authorization_code`

  let ret = await httpcli.get(auth_url)
    .then(res => {
      return res.json()
    })
  c.send(tok.make(ret))
    
   
})
app.run(2005)